<template>
	<view class="login">
		<image src="http://qianxueapplet.suoeryun.com/loginBg.png" class="login_bg"></image>
		<view class="login_btm">
			<view class="login_btm_title">欢迎使用千寻研学游小程序</view>
			<button class="login_btm_btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"
				:loading="loading">获取用户信息</button>
			<image src="http://qianxueapplet.suoeryun.com/loginLogo.png" class="login_btm_logo"></image>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { wxPhoneLogin } from '@/config/login.api';
	import { onMounted, ref, unref } from "vue";
	const loginCode = ref();

	onMounted(() => {
		uni.login({
			success: (res) => {
				console.log(res);
				loginCode.value = res.code;
			}
		})
	})

	function login() {
		uni.checkSession({
			success(res) {
				if (res?.errMsg?.indexOf('ok') < 0) {
					uni.login({
						success: (res) => {
							console.log(res);
							loginCode.value = res.code;
						}
					})
				}
				console.log(res, 'checkSession');
			}, fail(err) {
				console.log(err, 'err');
			}
		})
	}
	/**
	 * 登录
	 */
	async function getPhoneNumber(e) {
		console.log(e, 'e');
		const { encryptedData, iv, errMsg } = e.detail;
		if (errMsg?.indexOf('ok') >= 0) {
			await login();
			uni.$u.vuex('loading', true);
			uni.getUserInfo({
				async success(data) {
					console.log(data, 'data', data?.userInfo);
					if (data?.errMsg?.indexOf('ok') >= 0) {
						let res = await wxPhoneLogin({ code: unref(loginCode), encryptedData, iv, ...data?.userInfo });
						uni.$u.vuex('loading', false);
						console.log(res, 'res');
						uni.$u.vuex('vuex_user', res.sysUser);
						uni.$u.vuex('vuex_token', res.token);
						uni.$u.vuex('vuex_openid', res.openid);
						uni.$u.route({
							type: 'switchTab',
							url: 'pages/index/index'
						})
					}
				},
				fail(err) {
					console.log(err, 'err');
				}
			})
		}
	}
</script>

<style lang="scss" scoped>
	.login {
		position: relative;

		.login_bg {
			width: 100vw;
			height: 100vh;
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
		}

		.login_btm {
			position: absolute;
			top: 57vh;
			left: 0;
			right: 0;
			text-align: center;

			.login_btm_title {
				font-size: 40rpx;
				color: #0D4D71;
				font-weight: 600;
			}

			.login_btm_btn {
				width: 290rpx;
				height: 76rpx;
				line-height: 76rpx;
				background-color: #FF943C;
				border-radius: 100px;
				margin: 62rpx auto 146rpx auto;
				color: #FFFFFF;
				font-size: 32rpx;
				font-weight: 600;

				&::after {
					border: 0;
				}
			}

			.login_btm_logo {
				width: 224rpx;
				height: 192rpx;
				margin: 0 auto;
			}
		}
	}
</style>